package com.xiang.dao;

import com.xiang.DBTest;
import com.xiang.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/9/14 20:58
 */
public class UserDaoImpl implements UserDao {
    private static PreparedStatement statement = null;


    public boolean getLogin(User user) {
        Connection connection = DBTest.getConnection();
        try {
            statement = connection.prepareStatement("select * from webapp3.user where  username=? and  password=?");
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            ResultSet executeQuery = statement.executeQuery();
            if (executeQuery.next()) {
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public List<User> getList() {
        Connection connection = DBTest.getConnection();
        User user = new User();
        ArrayList<User> list = new ArrayList<>();
        try {
            PreparedStatement statement = connection.prepareStatement("select  * from  webapp3.user");
            ResultSet query = statement.executeQuery();
            while (query.next()) {
                String username = query.getString("username");
                user.setUsername(username);

                String password = query.getString("password");
                user.setPassword(password);

                list.add(user);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();

        } finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return list;
    }
}
